package com.example.yichuangyun.utils;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;

import java.util.regex.Pattern;

public class ScreenshotListener {
    private static final String[] KEYWORDS = {
            "screenshot", "screen_shot", "screen-shot", "screen shot",
            "screencapture", "screen_capture", "screen-capture", "screen capture",
            "screencap", "screen_cap", "screen-cap", "screen cap"
    };
    private final Handler handler = new Handler();
    private final Context context;
    private ContentObserver observer;
    private boolean isScreenshot;
    private ScreenshotsListener screenshotsListener;

    public ScreenshotListener(Context context) {
        this.context = context;
    }

    public void startListening() {
        observer = new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange, Uri uri) {
                super.onChange(selfChange, uri);
                if (uri != null) {
                    String path = getPathFromUri(uri);
                    if (!isScreenshot) {
                        if (isScreenshot(path)) {
                            screenshotsListener.onScreenshots();
                            handler.postDelayed(() -> isScreenshot = false, 2000);
                            isScreenshot = true;
                        }
                    }
                }
            }
        };
        context.getContentResolver().registerContentObserver(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                true,
                observer
        );
    }

    private String getPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                String path = cursor.getString(column_index);
                cursor.close();
                return path;
            }
            cursor.close();
        }
        return null;
    }

    private boolean isScreenshot(String path) {
        if (path == null) {
            return false;
        }
        path = path.toLowerCase();
//        String screenshotPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath().toLowerCase();
        String screenshotPath = getRoute().toLowerCase();
        if (!path.startsWith(screenshotPath)) {
            return false;
        }
        for (String keyword : KEYWORDS) {
            if (Pattern.compile(keyword).matcher(path).find()) {
                return true;
            }
        }
        return false;
    }

    private String getRoute() {
        String route;
        String brand = Build.BRAND.toUpperCase();//获取手机厂商转大写
        switch (brand) {
            case "HUAWEI": //华为（已确认）
            case "HONOR": //荣耀
            case "MEIZU": // 魅族
            case "SAMSUNG": //三星
                route = "/Pictures/Screenshots";
                break;
            case "XIAOMI": //小米
            case "REDMI": //红米（已确认）
            case "VIVO": //vivo（已确认）
            case "OPPO": //oppo
                route = "/DCIM/Screenshots";
                break;
            default:
                route = "/Pictures/Screenshots";
        }
        return Environment.getExternalStorageDirectory() + route;
    }

    public void stopListening() {
        if (observer != null) {
            context.getContentResolver().unregisterContentObserver(observer);
            observer = null;
        }
        handler.removeCallbacksAndMessages(null);
    }

    public void setScreenshotsListener(ScreenshotsListener listener) {
        screenshotsListener = listener;
    }

    public interface ScreenshotsListener {
        void onScreenshots();
    }
}
